package main

/**
 * @Author: DengLibin
 * @Date: Create in 2023-01-16 18:06:00
 * @Description:
 给你两个整数数组 nums1 和 nums2 ，请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数，
 应与元素在两个数组中都出现的次数一致（如果出现次数不一致，则考虑取较小值）。可以不考虑输出结果的顺序。




示例 1：

输入：nums1 = [1,2,2,1], nums2 = [2,2]
输出：[2,2]
示例 2:

输入：nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出：[4,9]
*/

/**
 * @Author: DengLibin
 * @Date: Create in 2023-01-16 18:04:57
 * @Description: 思路 记录两个数组 中每个数出现的次数
 */
func intersect(nums1 []int, nums2 []int) []int {
	arrMin := nums1
	arrMax := nums2
	if len(nums1) > len(nums2) {
		arrMin = nums2
		arrMax = nums1
	}
	l := len(arrMin)
	m := make(map[int]int, l)

	for i := 0; i < l; i++ {
		v, has := m[arrMin[i]]
		if has {
			m[arrMin[i]] = v + 1
		} else {
			m[arrMin[i]] = 1
		}
	}
	m2 := make(map[int]int, len(arrMax))
	for i := 0; i < len(arrMax); i++ {
		v, has := m2[arrMax[i]]
		if has {
			m2[arrMax[i]] = v + 1
		} else {
			m2[arrMax[i]] = 1
		}
	}

	arr := make([]int, 0, l)
	for k, v := range m {
		num2, has := m2[k]
		if has {
			minNum := v
			if num2 < minNum {
				minNum = num2
			}
			for i := 0; i < minNum; i++ {
				arr = append(arr, k)
			}
		}
	}
	return arr
}
